class Joystick {
	joystick: HTMLCanvasElement
	ctx: CanvasRenderingContext2D | null
	isDown: boolean = false
	position = { x: 0, y: 0 }
	radius: number = 50
	constructor(container: string) {
        console.log('container',container)
		this.joystick = document.getElementById(container) as HTMLCanvasElement
        this.ctx = this.joystick?.getContext('2d')
		this.init()
	}
    // 初始化
    init() {
		// 鼠标按下事件
		this.joystick.onmousedown = e => {
			this.isDown = true
			let mouseX = e.pageX - this.joystick.offsetLeft
			let mouseY = e.pageY - this.joystick.offsetTop
			if (Math.sqrt(Math.pow(mouseX - this.position.x, 2) + Math.pow(mouseY - this.position.y, 2)) < this.radius) {
				this.position.x = mouseX
				this.position.y = mouseY
			}
		}
		// 鼠标移动事件
		this.joystick.onmousemove = e => {
			if (this.isDown) {
				let mouseX = e.pageX - this.joystick.offsetLeft
				let mouseY = e.pageY - this.joystick.offsetTop
				this.position.x = mouseX
				this.position.y = mouseY
			}
		}
		// 鼠标抬起事件
		this.joystick.onmouseup = e => {
			this.isDown = false
			this.position.x = 100
			this.position.y = 100
		}
        this.loop()
    }
	// 绘制圆盘
	drawJoystick() {
		if (!this.ctx) return
		this.ctx.beginPath()
		this.ctx.arc(this.position.x, this.position.y, this.radius, 0, 2 * Math.PI)
		this.ctx.fillStyle = 'gray'
		this.ctx.fill()
		this.ctx.lineWidth = 2
		this.ctx.strokeStyle = 'black'
		this.ctx.stroke()
	}
	// 计算方向
	getDirection(x: number, y: number) {
		let angle = Math.atan2(y - 100, x - 100)
		if (angle < 0) angle += 2 * Math.PI
		const octants = ['北', '北东', '东', '南东', '南', '南西', '西', '北西']
		const octant = Math.round(angle * (8 / Math.PI) + 0.5) % 8
		return octants[octant]
	}
	// 绘制圆盘并获取方向
	loop() {
		if (!this.ctx) return
		this.ctx.clearRect(0, 0, this.joystick.width, this.joystick.height)
		this.drawJoystick()
		const direction = this.getDirection(this.position.x, this.position.y)
		console.log(direction)
		requestAnimationFrame(this.loop)
	}
}

export default Joystick
